/*
 *  Pedometer - Android App
 *  Copyright (C) 2009 Levente Bagi
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package chinlone.pedometer;


import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;



import chinlone.pedometer.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.database.sqlite.*;



public class Pedometer extends Activity {
	private static final String TAG = "Pedometer";
	private static final Timer timer = new Timer();
	private TimerTask task;
    private SharedPreferences mSettings;
    private PedometerSettings mPedometerSettings;
    private Utils mUtils;
    
    
    private TextView mStepValueView;
    //private TextView mPaceValueView;
    private TextView mDistanceValueView;
  //  private TextView mSpeedValueView;
    private TextView mCaloriesValueView;
 //   private TextView mDesiredPaceView;
    private int mStepValue = 0;
    private int minuteStep = 0;
//    private int mPaceValue;
    private float mDistanceValue = 0;
    private float mStepLength = 0; 
    
 //   private float mSpeedValue;
    private int mCaloriesValue = 0;//卡路里
//    private float mDesiredPaceOrSpeed;
    private int mMaintain;
    private boolean mIsMetric;
    private float mMaintainInc;
    private boolean mQuitting = false; // Set when user selected Quit from menu, can be used by onPause, onStop, onDestroy

  
    private DBManager dbm; 
    private LocationClient mLocClient;
    //定位结果
    private BDLocation locationMsg = null;
  
    /**
     * True, when service is running.
     */
    private boolean mIsRunning;
   
  //设置百度定位的相关参数
  		private void setLocationOption(){
  			LocationClientOption option = new LocationClientOption();  			
  			option.setOpenGps(true);				//打开gps
  			option.setCoorType("bd09ll");		//设置坐标类型
  			option.setServiceName("com.baidu.location.service_v2.9");
  			option.setProdName("chinlone。pedometer"); //设置产品线名字
  			//option.setAddrType("all"); //设置是否需要地址信息
  			option.setScanSpan(5000); //设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
  			//	option.setPriority(LocationClientOption.NetWorkFirst);      //设置网络优先  			
  			option.setPriority(LocationClientOption.GpsFirst);        //不设置，默认是gps优先  			
  			//option.setPoiNumber(10);
  			option.disableCache(true);		
  			//mLocClient.setLocOption(option);
  		}
  	//获取百度定位数据
  		public BDLocation  getLocation(){
			if (mLocClient != null && mLocClient.isStarted()){
				setLocationOption();
				mLocClient.requestLocation();	
				
			}				
			else 
			{
				Log.d("xyz:", "locClient is null or not started");
			
			}
			return ((Location)getApplication()).retLocation;
		}	
  		
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {    	
    		
        Log.i(TAG, "[ACTIVITY] onCreate");
        super.onCreate(savedInstanceState);      
       
      //  mStepValue = 0;
        
  //      mPaceValue = 0;
        
        setContentView(R.layout.main);
       /**
        *   
                           配置引导界面代码
        Intent intent =new Intent(Pedometer.this,Guide.class); 
     	startActivity(intent); 
     	Pedometer.this.finish();
        */
        mUtils = Utils.getInstance();
        
        task = new TimerTask() {
        	
        	public void run() { 
        		
                mHandler.sendMessage(mHandler.obtainMessage(TIME_MSG, 0, 0));
            }
        };
        timer.schedule(task, 1000 * 60, 1000 * 60);//一分钟执行一次定时任务
        dbm = new DBManager(this); 
 //定位开始       
        /*
        mLocClient = ((Location)getApplication()).mLocationClient;
        setLocationOption();
        mLocClient.start();
     */
		 
        /*
        ArrayList<Person> persons = new ArrayList<Person>();  
        
        Person person1 = new Person("Ella", 22, "lively girl");  
        Person person2 = new Person("Jenny", 22, "beautiful girl");  
        Person person3 = new Person("Jessica", 23, "sexy girl");  
        Person person4 = new Person("Kelly", 23, "hot baby");  
        Person person5 = new Person("Jane", 25, "a pretty woman");  
          
        persons.add(person1);  
        persons.add(person2);  
        persons.add(person3);  
        persons.add(person4);  
        persons.add(person5); 
        dbm.add(persons);
        */
    	
    }
    
    @Override
    protected void onStart() {
        Log.i(TAG, "[ACTIVITY] onStart");
        super.onStart();
        
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "[ACTIVITY] onResume");
        super.onResume();
        
        mSettings = PreferenceManager.getDefaultSharedPreferences(this);
        mPedometerSettings = new PedometerSettings(mSettings);
        
       // mUtils.setSpeak(mSettings.getBoolean("speak", false));
        
        // Read from preferences if the service was running on the last onPause
        mIsRunning = mPedometerSettings.isServiceRunning();
        
        // Start the service if this is considered to be an application start (last onPause was long ago)
        if (!mIsRunning && mPedometerSettings.isNewStart()) {
            startStepService();
            bindStepService();
        }
        else if (mIsRunning) {
            bindStepService();
        }
        
        mPedometerSettings.clearServiceRunning();

        mStepValueView     = (TextView) findViewById(R.id.step_value);
 //       mPaceValueView     = (TextView) findViewById(R.id.pace_value);
        mDistanceValueView = (TextView) findViewById(R.id.distance_value);
 //       mSpeedValueView    = (TextView) findViewById(R.id.speed_value);
        mCaloriesValueView = (TextView) findViewById(R.id.calories_value);
       // mCaloriesValueView.setText(Integer.toString(mCaloriesValue));
        mCaloriesValueView.setText("" + mCaloriesValue);
 //       mDesiredPaceView   = (TextView) findViewById(R.id.desired_pace_value);
        mStepLength = mPedometerSettings.getStepLength();
   //     if(mStepLength < 0) mStepLength = 0;

        mIsMetric = mPedometerSettings.isMetric();
        ((TextView) findViewById(R.id.distance_units)).setText(getString(
                mIsMetric
                ? R.string.kilometers
                : R.string.miles
        ));

    }
    /*
    private void displayDesiredPaceOrSpeed() {
        if (mMaintain == PedometerSettings.M_PACE) {
            mDesiredPaceView.setText("" + (int)mDesiredPaceOrSpeed);
        }
        else {
            mDesiredPaceView.setText("" + mDesiredPaceOrSpeed);
        }
    }
    */
    @Override
    protected void onPause() {
        Log.i(TAG, "[ACTIVITY] onPause");
        if (mIsRunning) {
            unbindStepService();
        }
        if (mQuitting) {
            mPedometerSettings.saveServiceRunningWithNullTimestamp(mIsRunning);
        }
        else {
            mPedometerSettings.saveServiceRunningWithTimestamp(mIsRunning);
        }

        super.onPause();
      //  savePaceSetting();
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "[ACTIVITY] onStop");
        super.onStop();
    }

    protected void onDestroy() {
    	//db.close();
    	dbm.closeDB();
    	//定位结束
    //	mLocClient.stop();
        Log.i(TAG, "[ACTIVITY] onDestroy");
        super.onDestroy();
    }
    
    protected void onRestart() {
        Log.i(TAG, "[ACTIVITY] onRestart");
        super.onDestroy();
    }

 
  /*  
    private void savePaceSetting() {
        mPedometerSettings.savePaceOrSpeedSetting(mMaintain, mDesiredPaceOrSpeed);
    }
*/
    private StepService mService;
    
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = ((StepService.StepBinder)service).getService();

            mService.registerCallback(mCallback);
            mService.reloadSettings();
            
        }

        public void onServiceDisconnected(ComponentName className) {
            mService = null;
        }
    };
    

    private void startStepService() {
        if (! mIsRunning) {
            Log.i(TAG, "[SERVICE] Start");
            mIsRunning = true;
            startService(new Intent(Pedometer.this,
                    StepService.class));
        }
    }
    
    private void bindStepService() {
        Log.i(TAG, "[SERVICE] Bind");
        bindService(new Intent(Pedometer.this, 
                StepService.class), mConnection, Context.BIND_AUTO_CREATE + Context.BIND_DEBUG_UNBIND);
    }

    private void unbindStepService() {
        Log.i(TAG, "[SERVICE] Unbind");
        unbindService(mConnection);
    }
    
    private void stopStepService() {
        Log.i(TAG, "[SERVICE] Stop");
        if (mService != null) {
            Log.i(TAG, "[SERVICE] stopService");
            stopService(new Intent(Pedometer.this,
                  StepService.class));
        }
        mIsRunning = false;
    }
    
    private void resetValues(boolean updateDisplay) {
        if (mService != null && mIsRunning) {
            mService.resetValues();                    
        }
        else {
     //       mStepValueView.setText("0");
   //         mPaceValueView.setText("0");
    //        mDistanceValueView.setText("0");
  //          mSpeedValueView.setText("0");
    //        mCaloriesValueView.setText("0");
            SharedPreferences state = getSharedPreferences("state", 0);
            SharedPreferences.Editor stateEditor = state.edit();
            if (updateDisplay) {
                stateEditor.putInt("steps", 0);
                stateEditor.putInt("pace", 0);
                stateEditor.putFloat("distance", 0);
                stateEditor.putFloat("speed", 0);
                stateEditor.putFloat("calories", 0);
                stateEditor.commit();
            }
        }
    }

    private static final int MENU_SETTINGS = 8;
    private static final int MENU_QUIT     = 9;

    private static final int MENU_PAUSE = 1;
    private static final int MENU_RESUME = 2;
    private static final int MENU_RESET = 3;
    
    /* Creates the menu items */
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        /*
        if (mIsRunning) {
            menu.add(0, MENU_PAUSE, 0, R.string.pause)
            .setIcon(android.R.drawable.ic_media_pause)
            .setShortcut('1', 'p');
        }
        else {
            menu.add(0, MENU_RESUME, 0, R.string.resume)
            .setIcon(android.R.drawable.ic_media_play)
            .setShortcut('1', 'p');
        }
        menu.add(0, MENU_RESET, 0, R.string.reset)
        .setIcon(android.R.drawable.ic_menu_close_clear_cancel)
        .setShortcut('2', 'r');
        */
        menu.add(0, MENU_SETTINGS, 0, R.string.settings)
        .setIcon(android.R.drawable.ic_menu_preferences)
        .setShortcut('8', 's')
        .setIntent(new Intent(this, Settings.class));
        menu.add(0, MENU_QUIT, 0, R.string.quit)
        .setIcon(android.R.drawable.ic_lock_power_off)
        .setShortcut('9', 'q');
        return true;
    }

    /* Handles item selections */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        /*
            case MENU_PAUSE:
                unbindStepService();
                stopStepService();
                return true;
            case MENU_RESUME:
                startStepService();
                bindStepService();
                return true;
            case MENU_RESET:
                resetValues(true);
                return true;
                */
            case MENU_QUIT:
                resetValues(false);
                unbindStepService();
                stopStepService();
                mQuitting = true;
                finish();
                return true;
        }
        return false;
    }
    private int  getCalories(int mStepValue){
    	
    	//返回每分钟消耗的卡路里
    	minuteStep = mStepValue - minuteStep;
    	float magic= 0f;
    	float cal=0f;    	
    	float body = mPedometerSettings.getBodyWeight();//体重
    	if(minuteStep > 170) magic = 2.10f; //跑步（重度）
    	//中度
    	if(minuteStep < 170){
    		if(minuteStep > 100){
    			magic = 1.79f;
    		}
    		
    	}
    	//轻度
    	if(minuteStep < 100){
    		magic = 1.55f;    		
    	}
    	
    	if(mPedometerSettings.isMale()){
    		//男性
    		cal = (body*0.048f + 3.653f)*10f; //一小时消耗的卡路里
    		cal /= 60f;//1分钟消耗的卡路里		
    	}
    	else{
    		//女性
    		cal = (body*0.034f + 3.538f)*10f; //一小时消耗的卡路里
    		cal /= 60f;//1分钟消耗的卡路里
    	}
    	cal *= magic;
    	return Math.round(cal); 
    }
    // TODO: unite all into 1 type of message
    private StepService.ICallback mCallback = new StepService.ICallback() {
        public void stepsChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(STEPS_MSG, value, 0));
        }
     
    };
    
    private static final int STEPS_MSG = 1;
    private static final int TIME_MSG = 2;
    /*
    private static final int PACE_MSG = 2;
    private static final int DISTANCE_MSG = 3;
    private static final int SPEED_MSG = 4;
    private static final int CALORIES_MSG = 5;
  */  
    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                case STEPS_MSG:
                    mStepValue = (int)msg.arg1;
                    mStepValueView.setText("" + mStepValue);
                    //mDistanceValue = (mStepLength * mStepValue);
                    /*
                    mDistanceValue += (float)(// kilometers
                            mStepLength // centimeters
                            / 100000.0); // centimeters/kilometer
                    mDistanceValueView.setText(
                            ("" + (mDistanceValue + 0.000001f)).substring(0, 5)
                    );
                    */
                    
                    mDistanceValue = mStepLength * mStepValue;    
                    
                    if (mDistanceValue < 100) { 
                    	mDistanceValue = 0;
                        mDistanceValueView.setText("0");
                    }
                    else {
                    		//mDistanceValue /= 100f;//厘米换算成米
                    		mDistanceValue /= 100000.0f;//米换算成公里
                        	mDistanceValueView.setText(
                                ("" + (mDistanceValue + 0.000001f)).substring(0, 5)
                        );
                    }
                    
                    /* 百度定位数据
                  //记步开始时，获取百度定位数据
                    locationMsg = getLocation();
                    Log.e("xyz:",Integer.toString(mStepValue));
                    if(null != locationMsg)
                    {
                    	//httpPost hp = new httpPost();
                    	
                    	Log.e("xyz错误码:",Integer.toString(locationMsg.getLocType()));
                    	Log.e("xyz纬度:",Double.toString(locationMsg.getLatitude()));
                    	Log.e("xyz经度:",Double.toString(locationMsg.getLongitude()));
                    	
                    }
                    else
                    {
                    	Log.e("xyz:","null!!!!!!!!!");
                    
                    }
                    */
                    break; 
                   
                case TIME_MSG:
                	
                	mCaloriesValue += getCalories(mStepValue);
                	
                	mCaloriesValueView.setText(Integer.toString(mCaloriesValue));
                	
                    break; 
                  
             
                default:
                    super.handleMessage(msg);
            }
        }
        
    };
    

}